

function LiveTVData() {
	this.storagename = "livetv_data7";
	
	this.auth = new Auth();
	this.livelist = new LiveList();
	this.itemlist = new LiveItemList();

	this.update = function() {
		this.auth.self = this;
		this.auth.oninit = function() {
			this.self.livelist.load( 1, this.getID() , true);
		}
		this.auth.init();
	}
	this.onupdate = function() {
		console.log("all data update!");
	}
	this.delayupdate = function( sec ) {
		setTimeout( this.update.bind(this) , sec * 1000 );
	}

	this.livelist.self = this;
	this.chandata = {};
	this.chandata.chan = {};
	this.livelist.onload = function( chns, cates ) {
		// alert("livelist load: " + JSON.stringify(cates) );
		this.self.chandata.catelist = cates;
		this.self.loadcate( 0 );
	}

	this.itemlist.self = this;
	this.itemlist.onload = function( chns ) {
		// console.log( this.self.cidx  + " loaded :" + JSON.stringify(chns) );
		this.self.chandata.catelist[this.self.cidx].chanlist = chns;
		// this.self.chandata.chan[this.cid] = chns;
		this.self.loadcate( this.self.cidx + 1 );
	}

	this.loadcate = function( idx ) {
		// console.log("load  : " + idx );
		if ( idx >= this.chandata.catelist.length ) {
			// console.log("load all cate over... " + idx );
			this.chandata.catelist = this.fixcatelist( this.chandata.catelist );
			var data = JSON.stringify(this.chandata);
			// console.log("init setitem : " + data.length + " : " + data );
			localStorage.setItem(this.storagename, data );
			this.onupdate();
			return;
		}

		this.cidx = idx;
		var cate = this.chandata.catelist[idx];
		this.onbeforeloadcate( cate );
		this.itemlist.load( cate.app_id, this.auth.getID() , true );
	}

	this.fixcatelist = function( ocatelist ) {
		var ncatelist = [];
		for( var i=0; i< ocatelist.length; i++  ) {
			// console.log( "fixcatelist: " + i );
			var chanlist = ocatelist[i].chanlist;
			// console.log( "fixcatelist: " + JSON.stringify(ocatelist[i]) );
			if ( !chanlist || chanlist.length == 0 ) 
				continue;
			ncatelist.push( ocatelist[i] );
		}
		return ncatelist;
	}

	this.onbeforeloadcate = function( cate ) {
	}

	this.init = function() {
		this.delayupdate( 10 );

		if( ! this.chandata.catelist ) {
			var data = localStorage.getItem( this.storagename );
			if ( !! data ) {
				// console.log("init getitem : " + data.length + " : " + data );
				this.chandata = JSON.parse(data);
			}
		}
		if( ! this.chandata.catelist || ! this.chandata.catelist.length ) 
			return false;
		this.chandata.catelist = this.fixcatelist( this.chandata.catelist );
		return true;
	}

	this.getcatelist = function() {
		return this.chandata.catelist;
	}

	this.fixchannum = function() {
		if( ! this.chandata.catelist ) return;
		var catelist = this.chandata.catelist;
		var count = 1;
		for( var i=0; i<catelist.length; i++ ) {
			var chanlist = catelist[i].chanlist;
			for( var j=0; j<chanlist.length; j++ ) {
				chanlist[j].tv_num_o = count++;
			}
		}
	}
	
}

